//
//  Ext+UIImage.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/8.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

extension UIImage {
    //UIImage 类方法
    class func screenShot()->UIImage? {
        //1 拿到主window
        let window = UIApplication.shared.keyWindow!
        //2 开启上下文
        UIGraphicsBeginImageContext(window.frame.size)
        //3 把window 上的内容渲染到上下文中
        //afterScreenUpdates 屏幕更新后在渲染 还是不更新后渲染
        window.drawHierarchy(in: window.frame, afterScreenUpdates: false)
        //4 从上下文中 获取image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //5关闭上下文
        UIGraphicsEndImageContext()
        return image
        
    }
    
    func dealImageScale(width: CGFloat) -> UIImage{
        if self.size.width <= width {
            return self
        }
        
        let h = width * self.size.height/self.size.width
        
        //开启上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: h))
        //把image 渲染到上下文中
        self.draw(in: CGRect(x: 0, y: 0, width: width, height: h))
        //从上下文中获取image
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        //关闭上下文
        UIGraphicsEndImageContext()
        return image
    }
    
}
